package com.foreknow.fliter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //注意：ServletRequest是HttpServletRequest父接口,因此需要强转
        //同样，ServletResponse是HttpServletResponse父接口,因此需要强转
        //在这里都是使用 HttpServletRequest 和  HttpServletResponse 所以需要强转类型
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
         //获取相对路径
        String servletPath = req.getServletPath();
//        resp.getWriter().println(servletPath);

        //session的名字
        HttpSession session = req.getSession();
        String name_session = (String) session.getAttribute("name");



        //如果不是登陆判定页面在进行拦截否则不拦截
        //登陆界面为login.jsp 登陆完毕需要在 /login2进行登陆验证，所以这里的路径写的是 /login2
        if(servletPath.equals("/login2")){

            chain.doFilter(req,resp);
        }
        else{
            //判断获取的session是否为空，空就跳转到登陆界面
            if(name_session != null){
                chain.doFilter(req,resp);
            }
            else{
                req.getRequestDispatcher("/login.jsp").forward(req,resp);

            }


        }


    }

    @Override
    public void destroy() {

    }
}
